<?php

/**
 * 板块管理
 * File Name：CustomBlockModel.php
 * File Encoding：UTF-8
 * File New Time：2014-5-20 10:32:28
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class CustomBlockModel extends BaseModel {

    public function tableName() {
        return '{{custom_block}}';
    }

    public function rules() {
        return array(
            array('block_title', 'required', 'message' => '板块标题不能为空！'),
            array('block_title', 'unique', 'allowEmpty' => false, 'message' => '该板块标题已经存在！'),
            array('start_time', 'required', 'message' => '开始时间不能为空！'),
            array('end_time', 'required', 'message' => '结束时间不能为空！'),
            //免验证
            array('type,goods_ids,listorder,status,goods_num,class_name', 'safe'),
        );
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 获取Level数组
     * @return array
     */
    public function getLevelArray() {
        //缓存key
        $key = "CustomBlock_getLevelArray";
        //读取缓存
        $cache = Yii::app()->cache->get($key);
        if (empty($cache)) {
            $cache = array(
                0 => '普通商品',
                1 => '首页显示',
                2 => '秒杀商品',
            );
            $data = $this->findAll($this->where(array('order' => 'listorder DESC,id ASC')));
            if (!empty($data)) {
                foreach ($data as $rs) {
                    $cache[$rs->id] = $rs->block_title;
                }
            }
            //默认缓存3600秒
            Yii::app()->cache->set($key, $cache, 3600);
        }
        return $cache;
    }

    public function getOnBlock($cache = true) {
        $key = "CustomBlockModel_getOnBlock";
        if (!$cache) {
            Yii::app()->cache->delete($key);
        }
        $return = Yii::app()->cache->get($key);
        if ($return) {
            return $return;
        }
        $blocks = $this->findAll('status = :status ORDER BY listorder DESC', array(':status' => 1));
        $return = array();
        if ($blocks) {
            foreach ($blocks as $key => $block) {
                $return[$key]['class_name'] = trim($block->class_name);
                $return[$key]['block_title'] = $block->block_title;
                $return[$key]['goods'] = GoodsModel::getCustomBlockGood($block->id, $block->goods_num);
            }
        }
        Yii::app()->cache->set($key, $return);
        return $return;
    }

}
